package org.swift.mashup.engine.model;

import java.util.HashMap;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.swift.mashup.engine.api.ScriptEngine;
import org.swift.mashup.engine.api.ScriptEngineProvider;

public class NamedScriptEngineProvider implements ScriptEngineProvider {
	private final static HashMap<String, ScriptEngineProvider> sharedProviders =
		new HashMap<String,ScriptEngineProvider>();
	
	private String jndiName;
	private ScriptEngineProvider provider;

	public NamedScriptEngineProvider(String jndiName) {
		this.jndiName = jndiName;
	}
	
	public NamedScriptEngineProvider(String jndiName, boolean autoInit) {
		this.jndiName = jndiName;
		if (autoInit){
			initProvider();
		}
	}

	public ScriptEngine getScriptEngine() throws Exception {
		initProvider();
		return provider.getScriptEngine();
	}

	private synchronized void initProvider() {
		if (provider == null) {
			try {
				Context initCtx = new InitialContext();
				provider = (ScriptEngineProvider) initCtx
						.lookup(jndiName);
			} catch (NamingException ne) {
				throw new RuntimeException("Failed to look up the octave"
						+ " engine provider using JNDI.", ne);
			}
		}
	}
	
	public static ScriptEngineProvider getSharedEngineProvider (String jndiName){
		ScriptEngineProvider provider = null;

		synchronized (sharedProviders){
			if (!sharedProviders.containsKey(jndiName)){
				sharedProviders.put(jndiName, new NamedScriptEngineProvider(jndiName,true));
			}
			provider = sharedProviders.get(jndiName);
		}

		return provider;
	}
}
